#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/07/20
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from datetime import datetime
from flask import render_template, json
from flask_login import current_user
from project.define import PermissionsModule, CarParkDefine
from project.flasky import app, db
from project.modules import *
from project.service import Service


def demo_database_init():
    """
    演示数据
    """
    MemberUser.table_init()
    RecordParking.table_init()
    RecordEntrance.table_init()
    RecordExit.table_init()
    ChargeDetail.table_init()

def database_init():
    """
    数据初始化
    """
    db.create_all()
    Role.table_init()
    User.table_init()
    Custom.table_init()
    # 测试数据
    DeviceGate.table_init()
    gates = DeviceGate.current_datas()
    DeviceCamera.table_init(*gates)
    DeviceLED168.table_init(*gates)
    DeviceCashier.table_init()
    CarParkSetting.table_init()
    CarParkPlace.table_init()
    CarParkRule.table_init()
    User.insert_default_cashier_user(*DeviceCashier.current_datas())
    MemberUser.table_init()

    
# 校验数据库
database_init()
CarParkService = Service(Debug=False)
CarParkService.service_start()


@app.context_processor
def inject_custom_info():
    """
    传递定制信息
    """
    ret = CarParkDefine.__dict__.copy()
    valid_roles = Role.roles_info()
    valid_gates = DeviceGate.current_datas()
    valid_cameras = DeviceCamera.current_datas()
    valid_cashiers = DeviceCashier.current_datas()
    ret['carpark_datetime'] = datetime.now().strftime("%Y/%m/%d %H:%M:%S")
    ret['page_user'] = current_user
    ret['permissions'] = PermissionsModule
    ret['custom'] = Custom.query.first()
    ret['ValidRoles'] = valid_roles
    ret['ValidGates'] = valid_gates
    ret['ValidGatesJSON'] = json.dumps(valid_gates,ensure_ascii=False)
    ret['ValidCameras'] = valid_cameras
    ret['ValidCamerasJSON'] = json.dumps(valid_cameras,ensure_ascii=False)
    ret['ValidCashiers'] = valid_cashiers
    ret['ValidCashiersJSON'] = json.dumps(valid_cashiers,ensure_ascii=False)
    ret['DebugState'] = CarParkService.Debug
    return ret


@app.errorhandler(404)
def page_not_found(error):
    """
    404错误处理
    """
    return render_template("error.html", error=error), 404


@app.errorhandler(403)
def page_forbid(error):
    """
    403错误处理
    """
    return render_template("error.html", error=error), 403


@app.errorhandler(500)
def internal_server_error(error):
    """
    500错误处理
    """
    return render_template("error.html", error=error), 500
